package com.platform.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.HashMap;
import java.util.Map;

public class BaiduIpUtil {

    public static String getCity(String ip) {
        String city = "";
        String url = "https://api.map.baidu.com/location/ip";

        Map<String, Object> params = new HashMap<>();
        params.put("ip", ip);
        params.put("ak", "Kh86YIWgdBHyuEG97ERsHmV3lahDnuWq");

        String jsonStr = HttpUtil.post(url, params);

        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        if (jsonObject == null) {
            System.out.println("百度IP定位请求失败");
            return city;
        }

        Integer status = jsonObject.getInt("status");
        if (status == null) {
            System.out.println("百度IP定位获取状态值失败");
            return city;
        }

        if (status != 0) {
            System.out.println("百度IP定位失败，原因：" + jsonObject.getStr("message"));
            return city;
        }

        JSONObject content = jsonObject.getJSONObject("content");
        if (content == null) {
            System.out.println("百度IP定位获取内容失败");
            return city;
        }

        JSONObject addressDetail = content.getJSONObject("address_detail");
        if (addressDetail == null) {
            System.out.println("百度IP定位获取地址详情失败");
            return city;
        }

        String ipCity = addressDetail.getStr("city");
        if (ipCity == null) {
            System.out.println("百度IP定位获取详情城市失败");
            return city;
        }

        return ipCity;
    }

}
